#pragma

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <string.h>
#include<functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace std;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR,
};
const static int defaulted = -1;
using hander_message_t =function<void(const int sockfd,const string message,const InetAddr who)>;
//typede function<string(const string&)> func_t
class Udpserver
{
public:
    Udpserver(uint16_t port,hander_message_t hander_message) : _sockfd(defaulted), _port(port), _isrunning(false),_hander_message(hander_message)
    {
    }
    // 1.初始化
    void InitServer()
    {
        // 1创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "sockfd error,%s,%d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success,socket:%d\n", _sockfd);

        // 2.0填充sockaddr_in结构
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); // 先清空
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); // 端口号要经过网络传输给对方，现在的port是主机序列
        // 所以要主机序列转网路序列
        // local.sin_addr.s_addr=inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;
        // 2.1bind sockfd和网络信息（IP+PORT）
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error,%s,%d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socket bind success\n");
    }
    void Start() // 对于服务器来说，他一直都是死循环，一般情况下不会退出
    {
        // UDP是面向数据报的数据
        _isrunning = true;
        while (true)
        {
            // 1.server先收数据，读数据用recvfrom
            char message[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                message[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG, "get message from [%s:%d] %s\n", addr.Ip().c_str(), addr.Port(), message);

                _hander_message(_sockfd,message,peer);

                // 2.server要把收到的数据，发回给对方
                //sendto(_sockfd, response.c_str(), sizeof(response), 0, (struct sockaddr *)&peer, len);
            }
        }
        _isrunning = false;
    }
    ~Udpserver()
    {
    }

private:
    int _sockfd;
    // string _ip;//不严谨要做修改
    uint16_t _port;
    bool _isrunning;

    //回调函数
    hander_message_t _hander_message;
};